import request from "./request";
import { requestWithAuth } from "./request";
import { ElMessage } from "element-plus";
import { validateUserData } from "@/utils/validators";
import cache from "@/utils/cache";

const CACHE_KEY = {
  USER_LIST: "user_list",
  USER_DETAIL: "user_detail_",
  USER_PROFILE: "user_profile",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取用户列表
 * @param {Object} params - 查询参数
 * @returns {Promise} - 返回用户列表数据
 */
export async function getUsers(params = {}) {
  try {
    const defaultParams = {
      search: "",
      sortBy: "nickName",
      ascending: true,
      page: 1,
      pageSize: 10,
    };
    const queryParams = { ...defaultParams, ...params };

    // 检查缓存
    const cacheKey = `${CACHE_KEY.USER_LIST}_${JSON.stringify(queryParams)}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await requestWithAuth({
      url: "/User/list",
      method: "get",
      params: queryParams,
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取用户列表失败");
  }
}

/**
 * 获取用户个人信息
 * @returns {Promise} - 返回用户个人信息
 */
export async function getUserProfile() {
  try {
    // 检查缓存
    const cachedData = cache.get(CACHE_KEY.USER_PROFILE);
    if (cachedData) {
      return cachedData;
    }

    const response = await requestWithAuth({
      url: "/User/profile",
      method: "get",
    });

    cache.set(CACHE_KEY.USER_PROFILE, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取用户信息失败");
  }
}

/**
 * 更新用户个人信息
 * @param {Object} profileData - 更新的用户信息
 * @returns {Promise} - 返回更新操作的结果
 */
export const updateUserProfile = async (profileData) => {
  try {
    const response = await requestWithAuth({
      url: "/User/profile",
      method: "PUT",
      data: profileData,
    });

    // 清除个人信息缓存
    cache.remove(CACHE_KEY.USER_PROFILE);
    return response;
  } catch (error) {
    handleError(error, "更新用户信息失败");
  }
};

/**
 * 微信登录
 * @param {Object} wechatCode - 微信登录码
 * @returns {Promise} - 返回登录结果
 */
export const wechatLogin = async (wechatCode) => {
  try {
    const response = await request({
      url: "/User/wechat-login",
      method: "POST",
      data: { code: wechatCode },
    });
    return response;
  } catch (error) {
    handleError(error, "微信登录失败");
  }
};

/**
 * 绑定手机号
 * @param {Object} phoneData - 手机号相关数据
 * @returns {Promise} - 返回绑定结果
 */
export const bindPhone = async (phoneData) => {
  try {
    if (!phoneData.phone) {
      throw new Error("手机号不能为空");
    }

    const response = await requestWithAuth({
      url: "/User/bindPhone",
      method: "POST",
      data: phoneData,
    });
    return response;
  } catch (error) {
    handleError(error, "绑定手机号失败");
  }
};

/**
 * 删除用户
 * @param {number} id - 要删除的用户ID
 * @returns {Promise} - 返回删除操作的结果
 */
export const deleteUser = async (id) => {
  try {
    if (!id) throw new Error("用户ID不能为空");

    const response = await request({
      url: `/User/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.USER_LIST);
    cache.remove(`${CACHE_KEY.USER_DETAIL}${id}`);

    return response;
  } catch (error) {
    handleError(error, "删除用户失败");
  }
};

/**
 * 创建新用户
 * @param {Object} userData - 新用户的数据
 * @returns {Promise} - 返回创建操作的结果
 */
export const createUser = async (userData) => {
  try {
    // 数据验证
    const validationResult = validateUserData(userData);
    if (!validationResult.isValid) {
      throw new Error(validationResult.message);
    }

    const response = await request({
      url: "/User/create",
      method: "POST",
      data: userData,
    });

    // 清除列表缓存
    cache.removeByPrefix(CACHE_KEY.USER_LIST);

    return response;
  } catch (error) {
    handleError(error, "创建用户失败");
  }
};

/**
 * 更新用户信息
 * @param {Object} userData - 更新的用户数据
 * @returns {Promise} - 返回更新操作的结果
 */
export const updateUser = async (userData) => {
  try {
    // 数据验证
    const validationResult = validateUserData(userData);
    if (!validationResult.isValid) {
      throw new Error(validationResult.message);
    }

    const response = await request({
      url: `/User/update/${userData.id}`,
      method: "PUT",
      data: userData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.USER_LIST);
    cache.remove(`${CACHE_KEY.USER_DETAIL}${userData.id}`);

    return response;
  } catch (error) {
    handleError(error, "更新用户信息失败");
  }
};

/**
 * 获取角色列表
 */
export async function getRoles() {
  try {
    const response = await requestWithAuth({
      url: "/Role/list",
      method: "get",
      headers: {
        "Request-Type": "getRoles",
      },
    });
    return {
      data: response.data.data || [],
    };
  } catch (error) {
    if (error.message === "重复请求已取消") {
      return { data: [] };
    }
    throw error;
  }
}

/**
 * 获取用户角色
 */
export async function getUserRoles(userId) {
  try {
    if (!userId) {
      throw new Error("用户ID不能为空");
    }

    const response = await requestWithAuth({
      url: `/User/roles`,
      method: "get",
      params: { userId },
      headers: {
        "Request-Type": `getUserRoles_${userId}`,
      },
    });

    return response;
  } catch (error) {
    if (error.message === "重复请求已取消") {
      return { data: [] };
    }
    throw error;
  }
}

/**
 * 保存用户角色
 * @param {number} userId - 用户ID
 * @param {number[]} roles - 角色ID数组
 * @returns {Promise} - 返回保存操作的结果
 */
export async function saveUserRoles(userId, roles) {
  if (!userId) {
    return Promise.reject(new Error("用户ID不能为空"));
  }
  if (!Array.isArray(roles) || roles.length === 0) {
    return Promise.reject(new Error("角色不能为空"));
  }

  const response = await requestWithAuth({
    url: "/User/assignRole",
    method: "post",
    data: {
      userId: userId,
      roles: roles,
    },
  });

  return response;
}
